var MJProto           = require('./MJProto');

cc.Class({
	extends: cc.Component,
	properties: {
		roomIDLabel: cc.Label,
		bureauLabel: cc.Label,
		maContent: cc.Node,
		maItem: cc.Node,
		MaJiangAtlas: cc.SpriteAtlas,
		mjResultNode: cc.Node,
		cardNode: cc.Node,
		/* pauseLabel: cc.Label, */
	},

	onLoad: function () {
		if (this.dialogParameters.reviewRecord) {
			this.reviewRecord = this.dialogParameters.reviewRecord;
		}
		else {
			let MJModel = require('./MJModel');
			this.reviewRecord = MJModel.getReviewRecord();
		}
		let lastItem = this.reviewRecord[this.reviewRecord.length-1];
		if (lastItem && !lastItem.result) {
			this.reviewRecord.pop();
		}
		this.tm = 0;
		this.bureau = 0;
		this.speed = 1;
		this.index = 0;
		this.pause = false;
		this.myUid = Global.UserModel.uid;
		this.setIndex(this.index);
		this.initHeads();
		let node = cc.find('Buttons', this.node);
		node.opacity = 125;
		node.runAction(cc.repeatForever(cc.sequence([
			cc.fadeTo(2, 0),
			cc.fadeTo(2, 125)
		])));
	},

	showButtons: function () {
		this.unscheduleAllCallbacks();
		let node = cc.find('Buttons', this.node);
		node.stopAllActions();
		node.opacity = 255;
		this.scheduleOnce(() => {
			node.runAction(cc.repeatForever(cc.sequence([
				cc.fadeTo(2, 0),
				cc.fadeTo(2, 125)
			])));
		}, 2);
	},

	preAct: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		let curIndex = this.index;
		-- this.index;
		if (this.index < 0) {
			this.index = 0;
		}
		if (curIndex != this.index) {
			this.setIndex(this.index);
		}
	},

	nextAct: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		let curIndex = this.index;
		++ this.index;
		let data = this.reviewRecord[this.bureau];
		if (this.index > data.operateRecord.length+1) {
			this.index = data.operateRecord.length+1;
		}
		if (curIndex != this.index) {
			this.setIndex(this.index);
		}
	},

	preResult: function () {
		this.preBureau();
		let data = this.reviewRecord[this.bureau];
		this.setIndex(data.operateRecord.length+1);
	},

	nextResult: function () {
		this.nextBureau();
		let data = this.reviewRecord[this.bureau];
		this.setIndex(data.operateRecord.length+1);
	},

	preBureau: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		let curBureau = this.bureau;
		-- this.bureau;
		if (this.bureau < 0) {
			this.bureau = 0;
		}
		if (this.bureau == curBureau) {
			return;
		}
		this.mjResultNode.active = false;
		this.index = 0;
		this.setIndex(this.index);
		this.initHeads();
	},

	nextBureau: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		let curBureau = this.bureau;
		++ this.bureau;
		let reviewRecord = this.reviewRecord;
		if (!reviewRecord[this.bureau]) {
			Global.DialogManager.addTipDialog(`暂时没有第${this.bureau+1}的数据`);
			-- this.bureau;
			return;
		}
		else {
			this.mjResultNode.active = false;
			this.index = 0;
			this.setIndex(this.index);
		}
		this.initHeads();
	},

	onPause: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		this.pause = !this.pause;
		if (this.pause) {
			/* this.pauseLabel.string = '继续'; */
		}
		else {
			/* this.pauseLabel.string = '暂停'; */
		}
	},

	speedUp: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		this.speed *= 2;
		if (this.speed > 8) {
			this.speed = 8;
		}
	},

	speedDown: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		this.speed /= 2;
		if (this.speed < 1/8) {
			this.speed = 1/8;
		}
	},

	speedNormal: function (event) {
		if (event) {
			Global.AudioManager.playCommonSoundClickButton();
			this.showButtons();
		}
		this.speed = 1;
	},

	update: function (dt) {
		this.tm += dt * this.speed;
		if (this.tm >= 1) {
			this.tm %= 1;
			if (!this.pause) {
				this.nextAct();
			}
		}
	},

	setIndex: function (index) {
		let data = this.reviewRecord[this.bureau];
		this.bureauLabel.string = '局数：'+(this.bureau+1)+'/'+data.maxBureau;
		this.roomIDLabel.string = '房号：'+data.roomID;
		let pengGangArrays = []; /* 碰杠的牌 */ 
		let outArrays = []; /* 出的牌 */ 
		let handArrays = []; /* 手牌 */ 
		for (let i = 0; i < data.handCards.length; ++i) {
			handArrays.push(data.handCards[i].slice());
			pengGangArrays.push([]);
			outArrays.push([]);
		}

		let lastItem = null;
		for (let i = 0; i < data.operateRecord.length && i <= index; ++i) {
			let item = data.operateRecord[i];
			if (item.operate == MJProto.operateType.GET) {
				handArrays[item.chairID].push(item.card);
			}
			else if (item.operate == MJProto.operateType.QI) {
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				outArrays[item.chairID].push(item.card);
			}
			else if (item.operate == MJProto.operateType.GANG_ZHI) {
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				pengGangArrays[item.chairID].push(item);
			}
			else if (item.operate == MJProto.operateType.GANG_BU) {
				for (let j = 0; j < pengGangArrays[item.chairID].length; ++j) {
					if (pengGangArrays[item.chairID][j].operate == MJProto.operateType.PENG && pengGangArrays[item.chairID][j].card == item.card) {
						pengGangArrays[item.chairID].splice(j, 1);
						break;
					}
				}
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				pengGangArrays[item.chairID].push(item);
			}
			else if (item.operate == MJProto.operateType.GANG_CHI) {
				for (let j = 0; j < outArrays.length; ++j) {
					if (outArrays[j].length > 0 && outArrays[j][outArrays[j].length-1] == item.card) {
						outArrays[j].pop();
						break;
					}
				}
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				pengGangArrays[item.chairID].push(item);
			}
			else if (item.operate == MJProto.operateType.PENG) {
				for (let j = 0; j < outArrays.length; ++j) {
					if (outArrays[j].length > 0 && outArrays[j][outArrays[j].length-1] == item.card) {
						outArrays[j].pop();
						break;
					}
				}
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				handArrays[item.chairID].splice(handArrays[item.chairID].indexOf(item.card), 1);
				pengGangArrays[item.chairID].push(item);
			}
			lastItem = item;
		}

		let lastOutChairID = null;
		let newCardChairID = null;
		let item = data.operateRecord[index];
		if (item && item.operate == MJProto.operateType.GET) {
			newCardChairID = item.chairID;
			let pre = data.operateRecord[index-1];
			if (pre && pre.operate == MJProto.operateType.QI) {
				lastOutChairID = pre.chairID;
			}
		}
		else if (item && item.operate == MJProto.operateType.QI) {
			lastOutChairID = item.chairID;
		}

		for (let i = 0; i < data.handCards.length; ++i) {
			let logic = this.getCardLogicByChairID(i);
			logic.clearAllCards();
			if (newCardChairID == i) {
				let card = handArrays[i].pop();
				logic.reset(handArrays[i], data.qidui);
				logic.getNewMj(card);
				Global.AudioManager.playSound('Game/Majiang/MJAudio/give');
			}
			else {
				logic.reset(handArrays[i], data.qidui);
				if (logic.dir == 0 && index >= data.operateRecord.length-1 && data.result.winChairIDArray.indexOf(i) != -1) {
					for (let node of logic._mjNodeList) {
						node.x += 82;
					}
				}
			}
			for (let j = 0; j < outArrays[i].length; ++j) {
				logic.addOutMj(outArrays[i][j], (i == lastOutChairID && j == (outArrays[i].length-1)));
				if (i == lastOutChairID && j == (outArrays[i].length-1) && item && item.card == outArrays[i][j]) {
					Global.AudioManager.playSound('Game/Majiang/MJAudio/nv/'+outArrays[i][j]);
					Global.AudioManager.playSound('Game/Majiang/MJAudio/push');
				}
			}
			let hasPeng = false;
			for (let j = 0; j < pengGangArrays[i].length; ++j) {
				let opeItem = pengGangArrays[i][j];
				if (opeItem.operate == MJProto.operateType.PENG) {
					hasPeng = true;
					logic.addOperMj([opeItem.card, opeItem.card, opeItem.card], 'peng', 1, opeItem == data.operateRecord[index]); 
					if (opeItem == data.operateRecord[index]) {
						Global.AudioManager.playSound('Game/Majiang/MJAudio/nv/peng');
					}
					if (opeItem == lastItem && logic._dir == 0) {
						for (let node of logic._mjNodeList) {
							node.x += 82;
						}
					}
				}
				else {
					logic.addOperMj([opeItem.card, opeItem.card, opeItem.card, opeItem.card], (opeItem.operate==MJProto.operateType.GANG_ZHI)? 'angang':'pinggang', 1, opeItem == data.operateRecord[index]);
					if (opeItem == data.operateRecord[index]) {
						Global.AudioManager.playSound('Game/Majiang/MJAudio/nv/gang');
					}
				}
			}
		}
		if (item) {
			let restCardsCount = data.cardsCount || 9*12+4;
			for (let i = 0; i < handArrays.length; ++i) {
				restCardsCount -= handArrays[i].length;
			}
			for (let i = 0; i < outArrays.length; ++i) {
				restCardsCount -= outArrays[i].length;
			}
			for (let i = 0; i < pengGangArrays.length; ++i) {
				for (let j = 0; j < pengGangArrays[i].length; ++j) {
					restCardsCount -= ((pengGangArrays[i][j].operate == MJProto.operateType.PENG)? 3:4);
				}
			}
			let clockLogic = cc.find('Clock', this.node).getComponent('MJReviewClock');
			clockLogic.setDir(item.chairID, data.handCards.length, restCardsCount);
			let bottomChairID = 0;
			for (let i = 0; i < data.userArray.length; ++i) {
				if (data.userArray[i].uid == this.myUid) {
					bottomChairID = i;
				}
			}
			clockLogic.setRotation(bottomChairID, data.handCards.length);
			let logic = this.getCardLogicByChairID(item.chairID);
			if (MJProto.operateType.HU_ZHI == item.operate) {
				logic.playOperAct('hu');
				Global.AudioManager.playSound('Game/Majiang/MJAudio/nv/zimo');
			}
			else if (MJProto.operateType.HU_CHI == item.operate) {
				logic.playOperAct('hu');
				Global.AudioManager.playSound('Game/Majiang/MJAudio/nv/hu');
			}
		}

		if (index >= data.operateRecord.length && data.result) { /* 显示码牌 */ 
			this.maContent.active = true;
			for (let node of this.maContent.children) {
				node.destroy();
			}
			let cards = data.result.myMaCards.slice();
			let nodeArray = [];
			for (let i = 0; i < cards.length; ++i) {
				let node = cc.instantiate(this.maItem);
				node.parent = this.maContent;
				node.active = true;
				nodeArray.push(node);
			}
			this.schedule(() => {
				if (nodeArray.length > 0) {
					let node = nodeArray.shift();
					let card = cards.shift().card;
					let name = "down2_"+Math.floor(card/10)+"_"+(card%10);
					node.getComponent(cc.Sprite).spriteFrame = this.MaJiangAtlas.getSpriteFrame(name);
				}
			}, 0, cards.length);
		}
		else {
			this.maContent.active = false;
			return;
		}
		if (this.handItemNodeArray) {
			for (let node of this.handItemNodeArray) {
				node.destroy();
			}
		}
		this.handItemNodeArray = [];
		if (index == data.operateRecord.length+1) { /* 显示结算界面 */ 
			this.mjResultNode.active = true;
			let posy = 350, itemHeight = 130;
			posy -= itemHeight/2;
			for (let i = 0; i < data.userArray.length; ++i) {
				let node = this.getHandCardsItem(
					data.userArray[i],
					data.result.handCards[i],
					pengGangArrays[i],
					data.result.scores[i],
					(data.result.winChairIDArray.indexOf(i) != -1)? data.result.myMaCards:null,
					this.getArrayItemCount(i, data.result.fangGangArray),
					data.result.huType
				);
				node.parent = this.mjResultNode;
				node.y = posy;
				posy -= itemHeight;
				this.handItemNodeArray.push(node);
			}
			posy += 60;

			/* 码牌 */
			let myMaCards = data.result.myMaCards;
			if (myMaCards && myMaCards.length > 0) {
				posy -= 20;
				let maLabel = cc.find('MaLabel', this.mjResultNode);
				maLabel.active = true;
				maLabel.y = posy;
				posy += 20;
				let maLayout = cc.find('ZhongMa', this.mjResultNode);
				for (let node of maLayout.children) {
					node.destroy();
				}
				maLayout.active = true;
				maLayout.y = posy;
				for (let i = 0; i < myMaCards.length; ++i) { /*马牌*/ 
					let node = this.getCardNode(myMaCards[i].card);
					cc.find('choosed', node).active = myMaCards[i].win;
					node.parent = maLayout;
					node.x = 18+37*i;
				}
				posy -= 70;
			}

			/* 剩余的牌 */
			posy -= 20;
			let restLabel = cc.find('RestLabel', this.mjResultNode);
			restLabel.y = posy;
			let restCards = data.result.restCards;
			let restLayout = cc.find('RestCards', this.mjResultNode);
			restLayout.y = posy + 20;
			for (let node of restLayout.children) {
				node.destroy();
			}
			for (let i = 0; i < restCards.length; ++i) {
				this.getCardNode(restCards[i]).parent = restLayout;
			}
		}
		else {
			this.mjResultNode.active = false;
		}
	},

	getHandCardsItem: function (user, handCards, pengGangArray, score, myMaCards, fangGangCount, huType) {
		let item = cc.instantiate(cc.find('Item', this.mjResultNode));
		cc.find('name', item).getComponent(cc.Label).string = user.nickname;
		cc.find('uid', item).getComponent(cc.Label).string = user.uid;
		Global.CCHelper.updateSpriteFrame(user.avatar, cc.find('head', item).getComponent(cc.Sprite));
		cc.find('banker', item).active = user.isBanker;

		let layout = cc.find('Layout', item);
		let posx = 0, cardWidth = 37, nullWidth = 10;
		posx += cardWidth/2;
		if (pengGangArray.length > 0) {
			for (let i = 0; i < pengGangArray.length; ++i) {
				let obj = pengGangArray[i];
				let count = (MJProto.operateType.PENG == obj.operate)? 3:4;
				let sumx = 0;
				for (let j = 0; j < count; ++j) {
					let card = (obj.operate == MJProto.operateType.GANG_ZHI && j < 3)? 0:obj.card;
					let node = this.getCardNode(card);
					node.parent = layout;
					if (count == 4 && j == 3) {
						node.y = 10;
						node.x = posx-2*cardWidth;
					}
					else {
						node.x = posx;
						posx += cardWidth;
					}
					sumx += node.x;
				}
				if (count == 4) {
					let label = cc.instantiate(cc.find('malabel', item));
					label.active = true;
					label.parent = item;
					label.x = sumx/4+layout.x;
					if (obj.operate == MJProto.operateType.GANG_ZHI) { /* 暗杠 */ 
						label.getComponent(cc.Label).string = '暗杠';
					}
					else if (obj.operate == MJProto.operateType.GANG_BU) { /* 明杠 */ 
						label.getComponent(cc.Label).string = '明杠';
					}
					else if (obj.operate == MJProto.operateType.GANG_CHI) { /* 接杠 */ 
						label.getComponent(cc.Label).string = '接杠';
					}
				}
				posx += nullWidth;
			}
		}

		if (myMaCards && myMaCards.length > 0) {
			cc.find('icon', item).active = true;
			for (let i = 0; i < handCards.length-1; ++i) {
				let node = this.getCardNode(handCards[i]);
				node.parent = layout;
				node.x = posx;
				posx += cardWidth;
				if (fangGangCount > 0 && i == handCards.length-2) {
					let label = cc.instantiate(cc.find('malabel', item));
					label.parent = item;
					label.active = true;
					label.getComponent(cc.Label).string = (fangGangCount == 1)? '放杠':'放杠x'+fangGangCount;
					label.x = node.x+layout.x;
				}
			}
			posx += nullWidth;
			let huCardNode = this.getCardNode(handCards[handCards.length-1]);
			huCardNode.parent = layout;
			huCardNode.x = posx;
			posx += cardWidth;
			let huNode = cc.find('hu', item);
			huNode.parent = huCardNode;
			huNode.active = true;
			huNode.setPosition(18, 25);
			posx += nullWidth;
			let resultLabel = cc.find('resultLabel', item);
			resultLabel.active = true;
			resultLabel.getComponent(cc.Label).string = (huType == MJProto.operateType.HU_ZHI)? '自摸':'抢杠';
		}
		else {
			for (let i = 0; i < handCards.length; ++i) {
				let node = this.getCardNode(handCards[i]);
				node.parent = layout;
				node.x = posx;
				posx += cardWidth;
				if (fangGangCount > 0 && i == handCards.length-1) {
					let label = cc.instantiate(cc.find('malabel', item));
					label.parent = item;
					label.active = true;
					label.getComponent(cc.Label).string = (fangGangCount == 1)? '放杠':'放杠x'+fangGangCount;
					label.x = node.x+layout.x;
				}
			}
		}

		if (score > 0) {
			let label = cc.find('win', item).getComponent(cc.Label);
			label.node.active = true;
			label.string = '+' + Math.floor(score);
		}
		else {
			let label = cc.find('lose', item).getComponent(cc.Label);
			label.node.active = true;
			label.string = Math.floor(score);
		}
		item.active = true;
		return item;
	},

	initHeads: function () {
		let data = this.reviewRecord[this.bureau];
		let headNames = ['Head1', 'Head2', 'Head3', 'Head4'];
		if (data.userArray.length == 2) {
			headNames = ['Head1', 'Head3', 'Head2', 'Head4'];
		}
		let bottomChairID = 0;
		let userArrayLen = data.userArray.length;
		for (let i = 0; i < userArrayLen; ++i) {
			if (data.userArray[i].uid == this.myUid) {
				bottomChairID = i;
			}
		}
		for (let i = 0; i < 4; ++i) {
			let chairID = (i-bottomChairID+4)%4;
			if (userArrayLen == 2) {
				chairID = (i-bottomChairID+2)%2;
				if (i == 2) {
					cc.find('Head2', this.node).active = false;
					cc.find('Head4', this.node).active = false;
					break;
				}
			}
			let name = headNames[chairID];
			let node = cc.find(name, this.node);
			let user = data.userArray[i];
			if (!user) {
				node.active = false;
			}
			else {
				node.active = true;
				Global.CCHelper.updateSpriteFrame(user.avatar, cc.find('head', node).getComponent(cc.Sprite));
				cc.find('banker', node).active = user.isBanker;
				cc.find('name', node).getComponent(cc.Label).string = user.nickname;
				cc.find('id', node).getComponent(cc.Label).string = Math.floor(user.score);
			}
		}
	},

	getCardLogicByChairID: function (chairID) {
		let data = this.reviewRecord[this.bureau];
		let cardNames = ['Cards1', 'Cards2', 'Cards3', 'Cards4'];
		if (data.userArray.length == 2) {
			cardNames = ['Cards1', 'Cards3', 'Cards2', 'Cards4'];
		}
		let bottomChairID = 0;
		for (let i = 0; i < data.userArray.length; ++i) {
			if (data.userArray[i].uid == this.myUid) {
				bottomChairID = i;
			}
		}
		let name = cardNames[(chairID-bottomChairID+4)%4];
		if (data.userArray.length == 2) {
			name = cardNames[(chairID-bottomChairID+2)%2];
		}
		let logic = cc.find(name, this.node).getComponent('MJReviewCards');
		logic.setChairCount(data.handCards.length);
		return logic;
	},

	onClose: function () {
		Global.DialogManager.destroyDialog("Game/Majiang/MJReviewDialog");
	},

	getCardNode: function (card) {
		let node = cc.instantiate(this.cardNode);
		card = (card <= 9)? '0'+card:''+card;
		node.active = true;
		node.y = 0;
		let name = "down2_"+Math.floor(card/10)+"_"+(card%10);
		node.getComponent(cc.Sprite).spriteFrame = this.MaJiangAtlas.getSpriteFrame(name);
		return node;
	},

	getNullNode: function () {
		let node = new cc.Node();
		node.width = 20;
		return node;
	},

	getArrayItemCount: function (item, array) {
		let count = 0;
		if (array && array.length > 0) {
			for (let i = 0; i < array.length; ++i) {
				if (array[i] == item) {
					++ count;
				}
			}
		}
		return count;
	},
});
